﻿/* common function using namespaces */

var CommonHelper = {

    ConvertJsonDate: function (jsonDate) {
        if (jsonDate != null && jsonDate != "") {
            return new Date(parseInt(jsonDate.substr(6)));
        }
        else {
            return "";
        }
    },

    GetSelectedSubMenu: function () {
        var url = document.URL.toLowerCase();
        var urlWithOutQueryString = "";

        if (url.indexOf("?") !== -1) {
            urlWithOutQueryString = url.split("?")[0];
        }
        else {
            urlWithOutQueryString = url;
        }

        if (urlWithOutQueryString.endsWith("/campaign/emailtemplate")) {
            urlWithOutQueryString = "/campaign/layoutemail";
        }
        else if (urlWithOutQueryString.endsWith("/banner/banner")) {
            urlWithOutQueryString = "/banner";
        }
        else if (urlWithOutQueryString.endsWith("/banner/resreward")) {
            urlWithOutQueryString = "/banner";
        }
        else if (urlWithOutQueryString.endsWith("/system/user_userrole")) {
            urlWithOutQueryString = "/system/userrole";
        }
        else if (urlWithOutQueryString.endsWith("/customer/detail")) {
            urlWithOutQueryString = "/customer";
        }

        $("div.content div.second-menu a").each(function () {
            var MenuLink = $(this).attr("href").toLowerCase();

            if (urlWithOutQueryString.endsWith(MenuLink)) {
                $(this).addClass("current");
            }
        });
    },

    GetSelectedLeftMenu: function (controllerName, action) {
        controllerName = controllerName.toLowerCase();
        action = action.toLowerCase();

        $("div.left-toolbars ul li a").each(function () {
            var MenuLink = $(this).attr("href").toLowerCase();

            if (MenuLink.indexOf(controllerName) != -1) {
                $(this).addClass("current");
            }
        });
    },

    ReorganizeLeftMenu: function () {
        $("#account-group li").each(function (index) {
            var indexProduct = 3;
            var indexReport = 9;
            var indexSystem = 11;

            if (index >= indexSystem) {
                $("#system-group").append($(this));
            }
            else if (index >= indexReport) {
                $("#report-group").append($(this));
            }
            else if (index >= indexProduct) {
                $("#product-group").append($(this));
            }
        });

        // hide disable link
        $(".left-toolbars ul li a.disable").parent().remove();

        // remove empty group
        $(".left-toolbars ul").each(function () {
            if ($(this).children().length == 0) {
                $(this).parent().prev().remove();
                $(this).parent().remove();
            }
        });
    },

    SetHeadingTitle: function (title) {
        $("h2#admin-title").html(title);
        document.title = title;
    },

    ShowMsg: function (message, MsgIconType) {
        if (MsgIconType != null) {
            message = "<span class='" + MsgIconType + "' style='float: left; margin: 0 7px 20px 0;'></span>" + message;
        }

        $.blockUI({
            theme: true,
            title: 'Message',
            message: "<p>" + message + "</p>",
        });
        $('.blockOverlay').click($.unblockUI);
    },

    AjaxLoading: function () {
        $.blockUI({
            theme: true,
            title: 'Message',
            message: "<p>Loading, please wait&nbsp;&nbsp;<img src='/Styles/Images/ajax-loader.gif' alt='' /></p>",
        });
    },

    StopAjaxLoading: function () {
        $.unblockUI();
    },

    FormatThousandSeperator: function (obj) {
        if ($(obj).val() != "" && $(obj).val() != "null") {
            $(obj).next().val($(obj).val());
            $(obj).digits();
        }
        else {
            $(obj).next().val("-1");
        }
    },

    RemoveThousandSeperator: function (obj) {
        var value = $(obj).val();
        value = value.replace(/,/g, '');
        $(obj).val(value);
    },

    PopupPage: function (Url, Width, Height) {
        var OffsetHeight = document.body.offsetHeight;
        var OffsettWidth = document.body.offsetWidth;
        var objWindow = window.open(Url, "", "width=" + Width + ",height=" + Height + ",resizable=1,scrollbars=yes,location=0");
        objWindow.moveTo((OffsettWidth - Width) / 2, /*(OffsetHeight - Height) / 2*/ 50);
    },

    Uploadify: function (btnUploadImageId, folder, isImage, txtImageUrlId, imgPreviewId) {
        $('#' + btnUploadImageId).uploadify({
            swf: '/Scripts/uploadify/uploadify.swf',
            uploader: '/Common/UploadFile?folder=' + folder + "&isImage=" + isImage,
            buttonClass: "uploadImage",
            buttonText: 'Upload',
            multi: false,
            sizeLimit: 1048576,
            cancelImg: '/Scripts/uploadify/uploadify-cancel.png',
            auto: true,
            onUploadSuccess: function (file, data, response) {
                data = jQuery.parseJSON(data);

                if (!(data.Message != null && data.Message != "")) {
                    $("#" + txtImageUrlId).val(data.Result);
                    $("#" + txtImageUrlId).trigger("change");
                    if (isImage) {
                        $("#" + imgPreviewId).attr("src", data.Optional);
                    }
                }
                else {
                    CommonHelper.ShowMsg("Error: " + data.Message, MsgIconType.Error);
                }
            }
        });
    },

    GetGenderString: function (genderId) {
        var result = "";

        switch (genderId) {
            case 0:
                result = "Not Set";
                break;
            case 1:
                result = "Male";
                break;
            case 2:
                result = "Female";
                break;
            default:
                result = "Not Set";
                break;
        }

        return result;
    },

    GetTaskStatusString: function (status) {
        var result = "";

        switch (status) {
            case 1:
                result = "<span class='red'>Open</span>";
                break;
            case 2:
                result = "In progress";
                break;
            case 3:
                result = "<span class='green'>Closed</span>";
                break;
            default:
                result = "Not Set";
                break;
        }

        return result;
    },

    GetOrderTypeString: function (orderType) {
        var result = "";

        if (orderType == "2") {
            result = "Advertising";
        }
        else {
            result = "Tool";
        }

        return result;
    },

    GetOrderStatusString: function (status) {
        var result = "";

        switch (status) {
            case 1:
                result = "Pending";
                break;
            case 2:
                result = "<span class='green'>Confirmed</span>";
                break;
            case 3:
                result = "<span class='green'>Completed</span>";
                break;
            case 4:
                result = "<span class='red'>Cancelled</span>";
                break;
            case 5:
                result = "Expired";
                break;
            case 6:
                result = "<span class='red'>Denied</span>";
                break;
            default:
                result = "Not Set";
                break;
        }

        return result;
    },

    HiddenInputSorting: function (className, value) {
        var result = "";

        result = "<input type='hidden' class='" + className + "' value='" + value + "' />";

        return result;
    },

    SelectResItemFormatResult: function (item) {
        var markup = "<table><tr>";

        if (item.PictureUrl !== undefined) {
            markup += "<td style='vertical-align:top'><img src='" + item.PictureUrl + "' width='75' /></td>";
        }

        markup += "<td style='vertical-align:top;padding-left:10px'><div style='font-weight:bold'>" + item.Name + "</div>";

        if (item.Address !== undefined) {
            markup += "<div>" + item.Address + "</div>";
        }

        markup += "</td></tr></table>"

        return markup;
    },

    SelectResItemFormatSelection: function (item) {
        return item.Name;
    }
};

ko.bindingHandlers.ckeditor = {
    init: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());

        $(element).html(value);

        var id = $(element).attr("id");
        var editor = CKEDITOR.instances[id];

        if (editor) {
            // editor.destroy(true);
            CKEDITOR.instances = new Array();
        }

        CKEDITOR.replace(id, {
            width: '750px',
            height: '300px',
            filebrowserImageUploadUrl: '/Content/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Images'
        });
    },
    update: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());

        $(element).html(value);

        var id = $(element).attr("id");
        var editor = CKEDITOR.instances[id];

        CKEDITOR.instances[id].setData(value);
    }
};

String.prototype.endsWith = function (suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

String.prototype.digits = function () {
    return this.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
};

$.fn.digits = function () {
    return this.each(function () {
        if ($(this).is('input:text')) {
            $(this).val($(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
        }
        else {
            $(this).text($(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
        }
    })
};

// Replaces all instances of the given substring.
String.prototype.replaceAll = function (
strTarget, // The substring you want to replace
strSubString // The string you want to replace in.
) {
    var strText = this;
    var intIndexOfMatch = strText.indexOf(strTarget);

    // Keep looping while an instance of the target string
    // still exists in the string.
    while (intIndexOfMatch != -1) {
        // Relace out the current instance.
        strText = strText.replace(strTarget, strSubString)

        // Get the index of any next matching substring.
        intIndexOfMatch = strText.indexOf(strTarget);
    }

    // Return the updated string with ALL the target strings
    // replaced out with the new substring.
    return (strText);
}

Date.prototype.addHours= function(h){
    this.setHours(this.getHours()+h);
    return this;
}

Date.isLeapYear = function (year) { 
    return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); 
};

Date.getDaysInMonth = function (year, month) {
    return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};

Date.prototype.isLeapYear = function () { 
    var y = this.getFullYear(); 
    return (((y % 4 === 0) && (y % 100 !== 0)) || (y % 400 === 0)); 
};

Date.prototype.getDaysInMonth = function () { 
    return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
};

Date.prototype.addMonths = function (value) {
    var n = this.getDate();
    this.setDate(1);
    this.setMonth(this.getMonth() + value);
    this.setDate(Math.min(n, this.getDaysInMonth()));
    return this;
};
